package com.kintreda.ieco_server.module.api.web;

import com.kintreda.ieco_server.bean.account.Organization;
import com.kintreda.ieco_server.bean.account.User;
import com.kintreda.ieco_server.bean.goods.Places;
import com.kintreda.ieco_server.bean.param.Echar;
import com.kintreda.ieco_server.bean.user.Statistics;
import com.kintreda.ieco_server.core.web.BaseController;
import com.kintreda.ieco_server.core.web.R;
import com.kintreda.ieco_server.module.account.service.IUserService;
import com.kintreda.ieco_server.module.order.service.*;
import com.kintreda.ieco_server.module.organization.service.IOrganizationService;
import com.kintreda.ieco_server.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/***
 * 后台用户Controller
 */
@Controller
@RequestMapping("/api/user")
public class ApiUserController extends BaseController{

	@Resource
	private IUserService userService;
	@Autowired
	private IRecycleRecordService recycleRecordService;
	@Autowired
	private IBuyRecordService buyRecordService;
	@Autowired
	private IStatisticsService statisticsService;
	@Autowired
	private IOrganizationService organizationService;
	@Autowired
	private IWasteService wasteService;
	@Autowired
	private IPlacesService placesService;


	/****************************************************************
	 * 添加用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/add",method=RequestMethod.POST)
	@ResponseBody
	public R add(User user) {

		return null;
	}

	@RequestMapping(value = "/changemoblie",method = RequestMethod.POST)
	@ResponseBody
	public Object changeMoblie(String openid,String moblie,String rmoblie){

		User user = userService.findUserByOpenId(openid);
		if (!rmoblie.equals(user.getMobile()+"")){
			return R.error("输入的旧号码有误,非当前号码");
		}

		if (userService.findByMobile(moblie)){
			return R.error("更换的手机号已被占用!");
		}
		user.setMobile(moblie);
		userService.update(user);
		return R.ok("修改成功");
	}

	/**
	 *
	 * 绑定手机号
	 * @param openid
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value = "/bing",method = RequestMethod.POST)
	@ResponseBody
	public Object bingMoblie(String openid,String mobile){
		try {
			if (userService.findByMobile(mobile)) {
				return R.error("该说手机号已经绑定!");
			}

			User userByOpenId = userService.findUserByOpenId(openid);
			userByOpenId.setMobile(mobile);
			userByOpenId.setIsBindingMobile(1);
			userService.update(userByOpenId);
			return R.ok("绑定成功!");
		}catch (Exception e){
			e.printStackTrace();
			return  R.error("系统异常稍后重试");
		}


	}


	@RequestMapping(value = "/updateuserinfor",method = RequestMethod.POST)
	@ResponseBody
	public Object updateUserInfor(String name,String avatar,String openid){
		User user = userService.findUserByOpenId(openid);
		if (user==null){
		user = new User();
		user.setOpenId(openid);
		user.setUserCode(name);
		user.setAvatar(avatar);
		user.setType("2");
		user.setName(name);
		//默认密码123456
		String pwd = new SimpleHash("MD5","123456",user.getSalt(),1).toString();
		user.setPassword(pwd);
		userService.save(user);
		}else {
			user.setName(name);
			user.setAvatar(avatar);
			user.setOpenId(openid);
			userService.update(user);
		}

		return R.ok();
	}




	@RequestMapping(value = "/infor",method = RequestMethod.POST)
	@ResponseBody
	public R infor(String openid){
		String userId;
		User user;
		try {
			 user = userService.findUserByOpenId(openid);
			 userId =user.getId();
			 String type = user.getType();
			 if (type.equals("3") || type.equals("4")){
				 String job = "";
			 	if (type.equals("3")){
					 job = organizationService.get(user.getOrgId()).getName() + "(管理员)";
				}
				 if (type.equals("4")){
					  job = organizationService.get(user.getOrgId()).getName() + "(成员)";
				 }
				 user.setUserCode(job);
			 	
			 }
		}catch (NullPointerException e){
			e.printStackTrace();
			String[] arr =new String[]{};
			Statistics statistics = new Statistics();
			statistics.setOther(arr);
			return R.error().put("statistics",statistics).put("wasteData",arr);
		}

		//小程序端验证登录逻辑
		//userId =  "d239470284a34bd285bc000a981de88b";
		JdbcTemplate jdbcTemplate = statisticsService.getJdbcTemplate();

		Statistics statistics = null;
		if (user.getType().equals("4") || user.getType().equals("3")){
			statistics = statisticsService.getByUserIdAndType(userId,"1");
		}else {
			statistics = statisticsService.getByUserIdAndType(userId,"0");
		}

		if (statistics==null){
			statistics = new Statistics();
			statistics.setUserId(userId);
			if (user.getType().equals("4") || user.getType().equals("3")){
				statistics.setType("1");
			}else {
				statistics.setType("0");
			}
			statisticsService.saveOrUpdate(statistics);
		}
		statistics.setUser(userService.get(userId));
		//购袋数量

		Double buycount = buyRecordService.count(userId);

		//装车
		Long close = recycleRecordService.countCloseByUserId(userId);
		statistics.setCar(close.doubleValue());

		//领用
		Places places = placesService.getByOrgId(userId, "0");
		if (places != null) {
			statistics.setClaim(places.getNum());
		}else {
			statistics.setClaim("0");
		}


		statistics.setSackNum(buycount+"");
		//收集数量
		Long recycount = recycleRecordService.count(userId);
		statistics.setNum(recycount+"");
		try{
			//总收入
			Long income = recycleRecordService.countIncome(userId);

			statistics.setSumBalance(income!=null?income+"":0+"");
		}catch (Exception e){
			e.printStackTrace();
		}

		//总投递量
		List<Long> gross = jdbcTemplate.queryForList("select sum(gross) from recyclerecord where userId = ? ", new Object[]{userId}, Long.class);
		try{
		Long gro = gross.size()>0?gross.get(0):0;
		statistics.setDeliveryQuantity(gro+"");
		}catch (Exception e){
			e.printStackTrace();
		}

		//不当次数
		List<Long> unsuitables = jdbcTemplate.queryForList("select count(id) from unsuitable where userId = ? and status = ? ", new Object[]{userId,"1"}, Long.class);
		Long unsuitable = unsuitables.size()>0?unsuitables.get(0):0;
		statistics.setMisconductNum(unsuitable+"");
		//用户
		statistics.setUser(user);

		//回收物品饼状图数据
		Object wasteData = wasteService.wasteDataByUserId(userId);


		//环保值
		Map<String, Object> epvalue = recycleRecordService.ePValueByUserId(userId);


		//统计近五个月的投递量
		List<Object> dates = DateUtil.getMonths(5);
		List<Object> echars = new ArrayList<>();
		int i =0;
		for (Object date : dates) {
			Echar echar = new Echar();
			try {
				List<Long> total = jdbcTemplate.queryForList("SELECT sum(gross) from recyclerecord where userId = ?  and date_format(createDate,'%Y-%m')= ? ", new Object[]{userId,date}, Long.class);
				Long methon = total.get(0);
				echar.setMonth(dates.get(i).toString());
				if (methon==null){
					echar.setTotal("0");
				}else {
					echar.setTotal(methon+"");
				}

			}catch (Exception e){
				echar.setMonth(dates.get(i).toString());
				echar.setTotal("0");
				e.printStackTrace();
			}
			echars.add(echar);
			i++;
		}
		statistics.setOther(echars);
		R r = R.ok();
		r.put("statistics",statistics);
		r.put("wasteData",wasteData);
		r.put("epvalue",epvalue);
		return r;
	}


	/**
	 * 判断用户是否是机构管理员
	 * @param openid
	 * @return
	 */
	@RequestMapping(value = "/isadmin",method = RequestMethod.POST)
	@ResponseBody
	public Object isAdmin(String openid){
		User user = userService.findUserByOpenId(openid);
		R r = R.ok();
		r.put("type",user.getType());
		if (StringUtils.equals(user.getType(),"3")){
			Organization org = organizationService.getOrgByAdminIdAndOrgStatus(user.getId());
			if (org==null){
				r.put("code","");
			}else {
				String code = org.getCode();
				r.put("code",code);
			}

		}else {
			r.put("code","");
		}

		return r;
	}


	/**
	 * 查询余额
	 *
	 */
	@RequestMapping(value = "/balance",method = RequestMethod.POST)
	@ResponseBody
	public Object query(String openid,String type){
		try {
			User  user = userService.findUserByOpenId(openid);
			Statistics statistics;
				if (type.equals("0")){
					if (user.getType().equals("3")){
						statistics =  statisticsService.getOrgStatistics(user.getOrgId());
					}else {
						statistics = statisticsService.getByUserIdAndType(user.getId(),"0");
					}
				}else {
					statistics = statisticsService.getByUserIdAndType(user.getId(),"1");
				}

				if (type.equals("3")){
					statistics = statisticsService.getByUserIdAndType(user.getId(),"0");
				}


				if (statistics==null){
					statistics = new Statistics();
				}

			R r = R.ok(" ");
			r.put("statistics",statistics);
			return r;
		}catch (Exception e){
			e.printStackTrace();
			return R.error("系统异常联系请管理员");
		}


	}






}
